using Keep.Service;
using Keep.Service.Impl;
using Keep.Util;
using Serilog;
using Serilog.Events;
using Serilog.Core;
using System.Text.Json.Serialization;
using System.Text.Json;
using Microsoft.Extensions.FileProviders;
using Keep.Const;
using Microsoft.AspNetCore.Http.Features;

var builder = WebApplication.CreateBuilder(args);

// 配置Serilog 
Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Override("Keep.*", LogEventLevel.Information) // 可选，调整Microsoft.*的日志级别
    .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {Message}{NewLine}{Exception}")
    .WriteTo.File(
        path: "logs/log-.txt",
        levelSwitch: new LoggingLevelSwitch(LogEventLevel.Warning),
        outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message} {SourceContext}{NewLine}{Exception}",
        rollingInterval: RollingInterval.Day,
        retainedFileCountLimit: 800, // 限制保留的文件数量
        flushToDiskInterval: TimeSpan.FromSeconds(5))// 可选，设置定时刷盘间隔
    .CreateLogger();

builder.Host.UseSerilog(); // 使用Serilog作为日志提供者

// 设置 Kestrel 服务器使用的地址和端口
builder.WebHost.ConfigureKestrel(options =>
{
    options.ListenAnyIP(8848); // 监听所有IP地址的8848端口
    // options.ListenAnyIP(3000, listenOptions =>
    // {
    //     listenOptions.UseHttps("certs/your_certificate.pfx", "yourSecurePassword");
    // });
});
// 注册 IHttpContextAccessor 服务
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

//控制器返回的结果类忽略掉值是空的属性
builder.Services.AddControllers().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
    options.JsonSerializerOptions.Converters.Add(new CustomDateTimeConverter());
});


builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
//依赖注入 Transient 每次使用都会创建一个新的
builder.Services.AddTransient<IFileService, FileServiceImpl>();
builder.Services.AddTransient<ILinkService, LinkServiceImpl>();
builder.Services.AddTransient<ILinkTypeService, LinkTypeServiceImpl>();
builder.Services.AddTransient<IMusicListService, MusicListServiceImpl>();
builder.Services.AddTransient<IMusicOfListService, MusicOfListServiceImpl>();
//项目支持跨域请求
builder.Services.AddCors(c =>
{
    c.AddPolicy("Cors", policy =>
    {
        // policy.WithOrigins("http://172.168.53.165:8080").WithOrigins("http://127.0.0.1:8080") // 明确指定前端的源
        // policy.AllowAnyOrigin() // 不明确指定前端的源
        //        .AllowAnyHeader()
        //        .AllowAnyMethod()
        //        .AllowCredentials(); // 明确允许凭据
        // policy.WithOrigins("http://tauri.localhost").AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
        policy.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
    });
});
//依赖注入 Scoped 只创建一次
builder.Services.AddScoped<IUserService, UserServiceImpl>();

// 增加 multipart 请求的最大大小
builder.Services.Configure<FormOptions>(options =>
{
    options.MultipartBodyLengthLimit = 26843545600; // 256*100 MB
});
//读取指定的配置文件
IConfiguration configuration = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json")
    .Build();
Dictionary<string, string> appSettings = configuration.AsEnumerable().ToDictionary(x => x.Key, x => x.Value);
string constr = appSettings["ConnectionStrings:Constr"];
string type = appSettings["ConnectionStrings:Type"];
Static.ReqUrl = appSettings["ReqUrl"];
string isdb = "true";

//获取当前项目下是否存在数据库文件
string filePath = constr.Split('=')[1];

if (File.Exists(filePath))
{
    isdb = "false";
}
SqlSugarHelper.SqlSugarInit(constr, type, isdb);
var app = builder.Build();

// 创建一个方法来简化静态文件中间件的添加
void AddStaticFiles(string physicalPath)
{
    string path = Path.Combine(builder.Environment.ContentRootPath, physicalPath);
    Directory.CreateDirectory(path);
    app.UseStaticFiles(new StaticFileOptions
    {
        FileProvider = new PhysicalFileProvider(path),
        RequestPath = "/" + physicalPath
    });
}
AddStaticFiles("File");
AddStaticFiles("Blog");
AddStaticFiles("BlogImg");
AddStaticFiles("Img");
AddStaticFiles("IconImg");
AddStaticFiles("Video");
AddStaticFiles("Music");
AddStaticFiles("MusicImg");
AddStaticFiles("Food");
AddStaticFiles("FoodImg");
AddStaticFiles("Thumbnail");

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseCors("Cors");

app.UseAuthorization();

app.MapControllers();
//尝试整合前端dist
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
    endpoints.MapFallbackToFile("index.html");
});

app.Run();

// 当应用关闭时，确保Serilog也停止并清理资源
Log.CloseAndFlush();